package com.gimi.cloud.jimi.manage.service.app.impl;


import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.MyBeanUtils;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.common.JmOperationLogService;
import com.gimi.cloud.jimi.dao.dao.homePage.AdDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnProdDao;
import com.gimi.cloud.jimi.dto.app.AdDTO;
import com.gimi.cloud.jimi.dto.app.ColumnDTO;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.product.ProductDto;
import com.gimi.cloud.jimi.entity.app.ColumnEntity;
import com.gimi.cloud.jimi.entity.app.ColumnProdEntity;
import com.gimi.cloud.jimi.manage.service.app.ColumnService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @auther loongs
 * @date 2017/12/27  15:43
 */
@Service
public class ColumnServiceImpl implements ColumnService {

    private ColumnDao columnDao;
    private ColumnProdDao columnProdDao;
    private JmOperationLogService jmOperationLogService;
    private AdDao adDao;
    private static final Logger logger = LoggerFactory.getLogger(ColumnServiceImpl.class);

    @Autowired
    public ColumnServiceImpl(ColumnDao columnDao, ColumnProdDao columnProdDao,
                             JmOperationLogService jmOperationLogService,AdDao adDao) {
        this.columnDao = columnDao;
        this.jmOperationLogService = jmOperationLogService;
        this.columnProdDao = columnProdDao;
        this.adDao = adDao;
    }


    @Override
    public Page<ColumnDTO> getColumnList(ColumnDTO columnDTO) {
        PageHelper.startPage(columnDTO.getCurrentPage(), columnDTO.getPageSize());
        List<ColumnDTO> result = columnDao.queryPageList(columnDTO);
        Page<ColumnDTO> page = new Page(new PageInfo<>(result));
        return page;
    }

    /**
     * 获得栏目商品列表（分页）
     * @param columnDTO
     * @return
     */
    @Override
    public Page<ColumnDTO> getPreColumnProdList(ColumnDTO columnDTO) {
        PageHelper.startPage(columnDTO.getCurrentPage(), columnDTO.getPageSize());
        List<ColumnDTO> result = columnDao.queryPageList(columnDTO);
        Date imgDate = AliOSSUtil.getNoEffictDateByDay(1);
        String cols = "";
        Map<Integer, ColumnDTO> colMap = new HashMap<>();
        for (ColumnDTO col : result) {
            cols += col.getColumnId() + ",";
            colMap.put(col.getColumnId(), col);
        }
        if(cols.endsWith(",")) {
            cols = cols.substring(0, cols.length() - 1);
        }
        List<AdDTO> proList = adDao.getListByColumnIds(cols);
        for (AdDTO pro : proList) {
            pro.setImgUrl(AliOSSUtil.getFileUrl(pro.getImgUrl(), imgDate));
            ColumnDTO col = colMap.get(pro.getColumnId());
            if(col != null) {
                if(col.getAdList() == null) {
                    List<AdDTO> adList = new ArrayList<>();
                    col.setAdList(adList);
                }
                col.getAdList().add(pro);
            }
        }
        List<ColumnDTO> colList = new ArrayList<>(colMap.values());

        Page<ColumnDTO> page = new Page(new PageInfo<>(colList));
        return page;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public boolean addColumn(ColumnDTO columnDTO) {
        //校验，如果已存在的栏目名不能再添加或者修改成为此栏目
        ColumnEntity columnEntityTemp = columnDao.selectColumnByName(columnDTO);
        if (columnEntityTemp != null) {
            throw new MsgException(ResponseCodeEnum.COLUMN_IS_EXIT);
        }
        //添加栏目对象
        ColumnEntity columnEntity = new ColumnEntity();
        BeanUtils.copyProperties(columnDTO, columnEntity);
        columnEntity.setColumnStatus(0);//初始得栏目状态 默认不可用0
        columnEntity.setCreateTime(new Date());
        columnEntity.setCreateId(columnDTO.getAddUid());
        Integer columnFlag = columnDao.insertSelective(columnEntity);

        //添加栏目商品关系对象
        Integer relationFlag = addColumnProd(columnEntity.getColumnId(),columnDTO.getProductList());

        if (columnFlag > 0 && relationFlag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(columnDTO, baseDTO);
            jmOperationLogService.insertAddLog(baseDTO, columnDTO.getColumnId() + "", "addColumn", "jimi_column", "添加栏目");
            return true;
        }
        return false;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean editColumn(ColumnDTO columnDTO) {
        //校验，如果已存在的栏目名不能再添加或者修改成为此栏目
        ColumnEntity columnEntityTemp = columnDao.selectColumnByName(columnDTO);
        if (columnEntityTemp != null && columnEntityTemp.getColumnId().intValue() != columnDTO.getColumnId().intValue()) {
            throw new MsgException(ResponseCodeEnum.COLUMN_IS_EXIT,"栏目名称已存在");
        }

        ColumnEntity columnEntity = columnDao.selectByPrimaryKey(columnDTO.getColumnId());
        MyBeanUtils.copyPropertiesIgnoreNull(columnDTO, columnEntity);
        columnEntity.setUpdateTime(new Date());
        columnEntity.setModifyId(columnDTO.getUpdateUid());
        Integer flag = columnDao.updateByPrimaryKey(columnEntity);

        //删除相关商品
        columnProdDao.deleteByColumnId(columnEntity.getColumnId());
        //添加栏目商品关系对象
        Integer relationFlag = addColumnProd(columnEntity.getColumnId(),columnDTO.getProductList());
        if (flag > 0 && relationFlag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(columnDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "editColumn",
                    "jimi_column", columnDTO.getColumnId() + "", "修改栏目");
            return true;
        }
        return false;
    }

    @Override
    public Map gotoEditColumn(ColumnDTO columnDTO) {
        Map result = new HashMap();
        ColumnEntity columnEntity = columnDao.selectByPrimaryKey(columnDTO.getColumnId());
        List<Map> checkedProdList = columnProdDao.getCheckedProdByColumnId(columnDTO.getColumnId());
        if(columnEntity == null){
            throw new MsgException(ResponseCodeEnum.INVALID,String.format("没有columnId为%d的栏目信息",columnDTO.getColumnId()));
        }
        if(checkedProdList == null || checkedProdList.size() < 1){
            throw new MsgException(ResponseCodeEnum.INVALID,String.format("没有columnId为%d的商品",columnDTO.getColumnId()));
        }
        result.put("column",columnEntity);
        result.put("checkedProdList",checkedProdList);
        //添加操作日志
        jmOperationLogService.insertQueryLog(new BaseDTO(), "gotoEditColumn",
                "jimi_column", columnDTO.getColumnId() + "", "转跳到修改栏界面");
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteColumn(ColumnDTO columnDTO) throws MsgException {
        ColumnEntity columnEntity = columnDao.selectByPrimaryKey(columnDTO.getColumnId());
        if (columnEntity == null) {
            throw new MsgException(ResponseCodeEnum.COLUMN_IS_NOT_EXIT);
        }
        //这个地方需要思考下 广告和主页广告需不需要做判断？
        //如果是启用栏目时候，判断一下该栏目下是否有配置广告
        if (1 == columnDTO.getColumnStatus()) {
            List<ColumnProdEntity> columnProdEntityList = columnProdDao.selectColumnProdByColumnId(columnDTO);
            if (columnProdEntityList == null || columnProdEntityList.size() == 0) {
                throw new MsgException(ResponseCodeEnum.COLUMN_DO_NOT_HAVE_AD_OR_PROD);
            }
        }
        Integer flag = columnDao.deleteColumn(columnDTO);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(columnDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "deleteColumn",
                    "jimi_column", columnDTO.getColumnId() + "", "启动/禁用指定栏目");
            return true;
        }
        return false;
    }

    @Override
    public List<ColumnEntity> selectAll() {
        return columnDao.selectAll();
    }

    /**
     * 添加栏目商品关系对象
     */
    private int addColumnProd(Integer columnId,List<ProductDto> productList){
        int result = 0;
        if(columnId == null || columnId.equals(0)){
            throw new MsgException(ResponseCodeEnum.INVALID,"获取栏目id失败");
        }
        if(productList == null || productList.size() < 1){
            throw new MsgException(ResponseCodeEnum.INVALID,"请选择栏目相关商品列表");//feign已经做了校验，一般不会走这个逻辑
        }
        List<ColumnProdEntity> columnProdList = new ArrayList<>();
        for(ProductDto product : productList){
            ColumnProdEntity columnProdEntity = new ColumnProdEntity();
            columnProdEntity.setColumnId(columnId);
            String sort = product.getSort() != null ? String.valueOf(product.getSort()) : "0";
            columnProdEntity.setSort(sort);
            columnProdEntity.setCreateTime(new Date());
            columnProdEntity.setProdId(product.getProdId());
            columnProdList.add(columnProdEntity);
        }
        int num = columnProdDao.insertList(columnProdList);
        if(num > 0){
            result = num;
        }
        return result;
    }

}
